# encoding=utf8
import json
import os

import yaml

from wox import Wox


def Init():
    is_file = os.path.isfile('config.yaml')
    if is_file:
        pass
    else:
        # 创建文件
        open('config.yaml', 'a')


def judge(data):
    f = open('./config.yaml')
    result = f.read()
    yamlCon = yaml.load(result, Loader=yaml.FullLoader)
    res_data = []
    for item in yamlCon:
        str_con = item['command']
        find_str = str_con.find(data)
        r = open('./log.txt', 'a', encoding='utf-8')
        r.write("查询数据为：" + str_con + "结果为：" + str(find_str))
        r.close()
        if find_str >= 0:
            tmp_obj = {
                'Title': 'Run:' + str_con,
                'SubTitle': 'Terminal',
                'IcoPath': 'Images/shell.png',
                'JsonRPCAction': {
                    'method': 'action',  # 使用的方法名
                    'parameters': [str_con],
                    'dontHideAfterAction': True
                }
            }
            res_data.append(tmp_obj)
    return res_data


class Main(Wox):

    def query(self, data):
        # 初始化判断文件是否存在
        Init()
        command = data[0:3]
        if command == "add":
            # 添加固定命令
            tmp_obj = [{
                'Title': 'Run:' + data,
                'SubTitle': 'Terminal',
                'IcoPath': 'Images/add.png',
                'JsonRPCAction': {
                    'method': 'addCommand',  # 使用的方法名
                    'parameters': [data[4:]],
                    'dontHideAfterAction': True
                }
            }]
            return tmp_obj
            pass
        else:
            # 传入参数判断是否使用过
            res_data = judge(data)
            tmp_obj = {
                'Title': 'Run:' + data,
                'SubTitle': 'Terminal',
                'IcoPath': 'Images/shell.png',
                'JsonRPCAction': {
                    'method': 'action',  # 選択時に呼ばれるメソッド名
                    'parameters': [data],
                    'dontHideAfterAction': True
                }
            }
            res_data.insert(0, tmp_obj)
            return res_data

        # 添加到日志文件
        # r = open('./log.txt', 'a', encoding='utf-8')
        # str_log = json.dumps(res_data)
        # r.write("执行true" + str_log)
        # r.close()

    def action(self, data):
        # 截取字符串判断

        cmd = "wt " + data
        os.system(cmd)
        pass

    def addCommand(self, data):
        f = open('./config.yaml')
        result = f.read()
        yamlCon = yaml.load(result, Loader=yaml.FullLoader)
        tmpList = yamlCon
        tmpList.append({'command': data})
        save_f = open('config.yaml', 'w', encoding='utf-8')
        yaml.dump(tmpList, save_f)
        cmd = "wt " + data
        os.system(cmd)
        pass


if __name__ == '__main__':
    Main()
